import LoginHeader from '@/components/login-header/index'
import FindPassword from '@/apis/FindPassword'
import SendCode from '@/apis/SendCode'
export default {
  components: {
    LoginHeader,
  },
  data() {
    return {
      inCode: '',
      inPassword: '',
      confirmPassword: '',
      CodeText: '获取验证码',
      countDown: 0,
      interval: '',
    }
  },
  methods: {
    backPage() {
      uni.navigateBack({
        delta: 1,
      })
    },
    getCode() {
      if (this.countDown > 0) {
        return
      }
      const _this = this
      uni.getStorage({
        key: 'phoneNumber',
        success: function(res) {
          const phoneNumber = res.data
          // 此处发送验证码请求
          SendCode({
            phone: phoneNumber,
          }).then((res) => {
            _this.$toast('发送成功')
            if (res.data.flag === true) {
              _this.countDown = 59
              _this.interval = setInterval(() => {
                _this.CodeText = _this.countDown
                if (_this.countDown === 0) {
                  _this.CodeText = '获取验证码'
                  clearInterval(_this.interval)
                } else {
                  _this.countDown--
                }
              }, 1000)
            } else {
              _this.$toast('该手机号尚未注册')
              setTimeout(() => {
                _this.backPage()
              }, 600)
            }
          })
        },
      })
    },
    login() {
      if (this.inCode === '') {
        this.$toast('输入的验证码不能为空')
        return
      } else if (this.inCode.length !== 4) {
        this.$toast('请输入正确的验证码')
        this.inCode = ''
        return
      } else if (this.inPassword === '') {
        this.$toast('输入的密码不能为空')
        return
      } else if (this.inPassword.length > 20 || this.inPassword.length < 6) {
        this.$toast('请输入正确长度的密码')
        this.inPassword = ''
        this.confirmPassword = ''
        return
      } else if (this.inPassword !== this.confirmPassword) {
        this.$toast('两次输入的密码不一致')
        this.inPassword = ''
        this.confirmPassword = ''
        return
      }
      const _this = this
      uni.getStorage({
        key: 'phoneNumber',
        success: function(res) {
          const phoneNumber = res.data
          FindPassword({
            phone: phoneNumber,
            newPassword: _this.inPassword,
            code: _this.inCode,
          }).then((res) => {
            if (res.data.flag === true) {
              _this.$toast('修改密码成功')
              clearInterval(_this.interval)
              setTimeout(() => {
                uni.navigateTo({
                  url: '/pages/login/main-login/index',
                })
              }, 600)
            } else {
              _this.$toast('验证码错误')
              _this.inCode = ''
            }
          })
        },
      })
    },
  },
}
